import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getMessagesList,
  getMessageDetail,
  markMessageAsRead,
  markAllMessagesAsRead,
  deleteMessage,
  deleteMessages,
  sendMessage,
  getMessageStatistics,
  getUnreadCount,
  MESSAGE_TYPES,
  MESSAGE_TYPE_TEXT,
  MESSAGE_TYPE_COLOR,
  formatMessageTime
} from '@/api/messages'

export const useMessageStore = defineStore('message', () => {
  // 响应式数据
  const messages = ref([])
  const loading = ref(false)
  const pagination = ref({
    page: 0,
    size: 20,
    total: 0
  })

  // 消息数据（从API获取）
  const initMessages = ref([])

  // 计算未读消息数量
  const unreadCount = computed(() => {
    return messages.value.filter(msg => !msg.isRead).length
  })

  // 按类型统计消息数量
  const messageStats = computed(() => {
    const stats = {
      unread: 0,
      system: 0,
      order: 0,
      finance: 0,
      review: 0
    }

    messages.value.forEach(msg => {
      if (!msg.isRead) {
        stats.unread++
      }
      stats[msg.type]++
    })

    return stats
  })

  // 加载消息列表
  const loadMessages = async (params = {}) => {
    try {
      loading.value = true

      const requestParams = {
        page: params.page || pagination.value.page,
        size: params.size || pagination.value.size,
        type: params.type || '',
        status: params.status || '',
        keyword: params.keyword || ''
      }

      const response = await getMessagesList(requestParams)

      if (response.code === 200) {
        messages.value = response.data.records || response.data || []
        pagination.value = {
          page: response.data.page || 0,
          size: response.data.size || 20,
          total: response.data.total || 0
        }
        console.log('✅ 消息列表加载成功')
      } else {
        throw new Error(response.message || '获取消息列表失败')
      }
    } catch (error) {
      console.error('❌ 获取消息列表失败:', error)
      ElMessage.error(error.message || '获取消息列表失败')
      // 使用示例数据作为备用
      messages.value = initMessages.value
    } finally {
      loading.value = false
    }
  }

  // 获取消息详情
  const getMessageDetailById = async (messageId) => {
    try {
      const response = await getMessageDetail(messageId)
      if (response.code === 200) {
        return response.data
      } else {
        throw new Error(response.message || '获取消息详情失败')
      }
    } catch (error) {
      console.error('获取消息详情失败:', error)
      ElMessage.error(error.message || '获取消息详情失败')
      return null
    }
  }

  // 标记消息为已读
  const markAsRead = async (messageId) => {
    try {
      const response = await markMessageAsRead(messageId)
      if (response.code === 200) {
        // 更新本地状态
        const message = messages.value.find(msg => msg.id === messageId)
        if (message && !message.isRead) {
          message.isRead = true
        }
        console.log('✅ 消息已标记为已读')
        return true
      } else {
        throw new Error(response.message || '标记已读失败')
      }
    } catch (error) {
      console.error('标记消息已读失败:', error)
      ElMessage.error(error.message || '标记已读失败')
      return false
    }
  }

  // 标记所有消息为已读
  const markAllAsRead = async () => {
    try {
      const unreadMessageIds = messages.value
        .filter(msg => !msg.isRead)
        .map(msg => msg.id)

      if (unreadMessageIds.length === 0) {
        return true
      }

      const response = await markAllMessagesAsRead(unreadMessageIds)
      if (response.code === 200) {
        // 更新本地状态
        messages.value.forEach(msg => {
          msg.isRead = true
        })
        console.log('✅ 所有消息已标记为已读')
        return true
      } else {
        throw new Error(response.message || '批量标记已读失败')
      }
    } catch (error) {
      console.error('批量标记消息已读失败:', error)
      ElMessage.error(error.message || '批量标记已读失败')
      return false
    }
  }

  // 删除消息
  const removeMessage = async (messageId) => {
    try {
      const response = await deleteMessage(messageId)
      if (response.code === 200) {
        // 更新本地状态
        const index = messages.value.findIndex(msg => msg.id === messageId)
        if (index > -1) {
          messages.value.splice(index, 1)
        }
        console.log('✅ 消息已删除')
        return true
      } else {
        throw new Error(response.message || '删除消息失败')
      }
    } catch (error) {
      console.error('删除消息失败:', error)
      ElMessage.error(error.message || '删除消息失败')
      return false
    }
  }

  // 批量删除已读消息
  const deleteAllRead = async () => {
    try {
      const readMessageIds = messages.value
        .filter(msg => msg.isRead)
        .map(msg => msg.id)

      if (readMessageIds.length === 0) {
        return true
      }

      const response = await deleteMessages(readMessageIds)
      if (response.code === 200) {
        // 更新本地状态
        messages.value = messages.value.filter(msg => !msg.isRead)
        console.log('✅ 已读消息已删除')
        return true
      } else {
        throw new Error(response.message || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除已读消息失败:', error)
      ElMessage.error(error.message || '批量删除失败')
      return false
    }
  }

  // 发送消息
  const sendNewMessage = async (messageData) => {
    try {
      const response = await sendMessage(messageData)
      if (response.code === 200) {
        // 添加到本地列表
        const newMessage = {
          id: response.data.id || Date.now(),
          isRead: false,
          createTime: new Date().toISOString(),
          ...messageData
        }
        messages.value.unshift(newMessage)
        console.log('✅ 消息发送成功')
        return response.data
      } else {
        throw new Error(response.message || '发送消息失败')
      }
    } catch (error) {
      console.error('发送消息失败:', error)
      ElMessage.error(error.message || '发送消息失败')
      return null
    }
  }

  // 获取消息统计
  const loadMessageStats = async () => {
    try {
      const response = await getMessageStatistics()
      if (response.code === 200) {
        return response.data
      } else {
        throw new Error(response.message || '获取消息统计失败')
      }
    } catch (error) {
      console.error('获取消息统计失败:', error)
      // 返回本地计算的统计
      return messageStats.value
    }
  }

  // 获取指定类型的消息
  const getMessagesByType = (type) => {
    if (type === 'all') {
      return messages.value
    }
    return messages.value.filter(msg => msg.type === type)
  }

  // 获取未读消息
  const getUnreadMessages = () => {
    return messages.value.filter(msg => !msg.isRead)
  }

  // 添加新消息（本地）
  const addMessage = (message) => {
    const newMessage = {
      id: Date.now(),
      isRead: false,
      createTime: new Date().toISOString(),
      ...message
    }
    messages.value.unshift(newMessage)
  }

  // 初始化store
  const initStore = async () => {
    await loadMessages()
  }

  return {
    // 状态
    messages,
    loading,
    pagination,

    // 计算属性
    unreadCount,
    messageStats,

    // 方法
    loadMessages,
    getMessageDetailById,
    markAsRead,
    markAllAsRead,
    removeMessage,
    deleteAllRead,
    sendNewMessage,
    loadMessageStats,
    getMessagesByType,
    getUnreadMessages,
    addMessage,
    initStore,

    // 常量
    MESSAGE_TYPES,
    MESSAGE_TYPE_TEXT,
    MESSAGE_TYPE_COLOR
  }
})
